package com.ztesoft.ip.jobs;

import java.io.File;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.xiaoleilu.hutool.CharsetUtil;
import com.xiaoleilu.hutool.FileUtil;
import com.xiaoleilu.hutool.Log;
import com.xiaoleilu.hutool.SecureUtil;
import com.xiaoleilu.hutool.Setting;
import com.xiaoleilu.hutool.db.DbUtil;
import com.xiaoleilu.hutool.db.Entity;
import com.xiaoleilu.hutool.db.handler.EntityListHandler;
import com.xiaoleilu.hutool.db.sql.SqlExecutor;
import com.ztesoft.ip.utils.DruidDatasource;
import com.ztesoft.ip.utils.EmailUtils;
import com.ztesoft.ip.utils.PropertiesUtil;

public class AutoSyhnDB implements Runnable {
	private static final Logger log = Log.get(AutoSyhnDB.class.getSimpleName());

	@Override
	public void run() {

		log.info("手动同步数据库任务启动...");
		PropertiesUtil.load("resouce/config", "value.config");

		String server = null;
		String email = null;
		String passwd = null;
		server = PropertiesUtil.getProperty("email_server");
		email = PropertiesUtil.getProperty("email_email");
		passwd = PropertiesUtil.getProperty("email_passwd_base64");
		passwd = SecureUtil.decodeBase64(passwd, CharsetUtil.UTF_8);
		EmailUtils eutil = new EmailUtils();
		eutil.init(server, email, passwd);
		Connection conn = null;
		CallableStatement c = null;
		try {
			conn = DruidDatasource.getConnection();
			File f = new File("resouce\\config\\calls.config");
			List<String> calls = FileUtil.readLines(f.getAbsolutePath(), CharsetUtil.UTF_8);
			for (String s : calls) {
				if (null != s && s.length() > 0) {
					log.info("sql:" + s);
					c = conn.prepareCall("{" + s + "}");
					c.execute();
				}
			}

			List<Entity> entityList = SqlExecutor.query(conn, "select * from DATA_PROCESS", new EntityListHandler());
			List<String> tables = new ArrayList<String>();
			for (Entity e : entityList) {
				tables.add(e.getStr("TABLE_NAME"));
			}
			for (String s : tables) {
				log.info("开始读取并更新表数据量" + s);
				List<Entity> count = SqlExecutor.query(conn, "select * from " + s, new EntityListHandler());
				if (null != count && count.size() > 0) {
					int co = count.size();
					int num = SqlExecutor.execute(conn, "UPDATE  DATA_PROCESS set cloumn_count = ? ,insert_time=sysdate,process_state=1,process_time=sysdate where table_name = ?", co, s);
				}
			}

			log.info("手动同步数据库任务全部完成!");
			File f1 = new File("resouce/config/value.config");
			Setting s = new Setting(f1, CharsetUtil.UTF_8, false);
			String[] ss = s.getStrings("getemails");
			for (String a : ss) {
				eutil.sendSimpleEmail(a, "智慧社区数据库同步报告", "智慧社区和大数据数据库同步今日同步已完成!", null);
			}
		} catch (SQLException | IOException e) {
			Log.error(log, e, "SQL error!");
			log.info("自动同步数据库任务执行异常!");
		} finally {
			DbUtil.close(conn);
		}

	}
}
